import eventBus from "@/eventBus.js";
import { debounce } from "@/utils/tools.js";
import wait from "@/assets/wait.svg";

let imgs = [];

const setImg = (img) => {
  //1.该图片是否已处理
  if (img.handled) {
    return;
  }
  img.dom.src = wait;
  //2.该图片是否在可视区内
  const clientHeight = document.documentElement.clientHeight;
  const { top, height } = img.dom.getBoundingClientRect();
  if (!(top > clientHeight || top < -height)) {
    const tempImg = new Image();
    tempImg.onload = () => {
      img.dom.src = img.src;
    };
    tempImg.src = img.src;
    img.handled = true;
  }
};

const setImgs = () => {
  imgs.forEach((img) => {
    setImg(img);
  });
};

eventBus.$on(
  "blogListScroll",
  debounce((blogItemBoxRef) => {
    setImgs();
  }, 100)
);

export default {
  inserted: function (el, binding) {
    const { value } = binding;
    imgs.push({
      dom: el,
      src: value,
      handled: false,
    });
    setImgs();
  },
  unbind: function (el, binding) {
    imgs = imgs.filter((item) => item.dom !== el);
  },
};
